<template>
  <div class="p-2">
    <!-- 容器 -->
    <div style="width: 70%">
      <!-- el-form 包裹整个表格 -->
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="auto"
      >
        <!-- 显示错误提示（可选） -->
        <el-form-item prop="datas" style="margin-top: 10px;">
          <div style="height: 20px; color: #f56c6c; font-size: 12px;">
            <!-- 错误信息会自动显示在这里 -->
          </div>
        </el-form-item>

        <el-table :data="datas" style="width: 100%" border>
          <!-- 组件类型 -->
          <el-table-column label="组件类型">
            <template #default="scope">
              <el-form-item
                :prop="'datas.' + scope.$index + '.type'"
                :rules="rules.type"
              >
                <el-select
                  v-model="scope.row.type"
                  placeholder="请选择组件类型"
                  @change="handleChangeType(scope.row)"
                >
                  <el-option label="图片" value="img" />
                  <el-option label="文字" value="text" />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>

          <!-- 内容设置 -->
          <el-table-column label="内容设置">
            <template #default="scope">
              <el-form-item
                :prop="'datas.' + scope.$index + '.content'"
                :rules="getDynamicContentRules(scope.row)"
              >
                <el-input
                  v-if="scope.row.type === 'text'"
                  v-model="scope.row.content"
                  placeholder="请输入内容"
                  type="textarea"
                />
                <JqtOssLibrary
                  v-if="scope.row.type === 'img'"
                  v-model="scope.row.content"
                  :data="scope.row.content"
                  :limit="1"
                  :isObject="false"
                />
              </el-form-item>
            </template>
          </el-table-column>

          <!-- 内容位置 -->
          <el-table-column label="内容位置">
            <template #default="scope">
              <el-form-item
                :prop="'datas.' + scope.$index + '.contentPosition'"
                :rules="rules.contentPosition"
              >
                <el-select
                  v-model="scope.row.contentPosition"
                  placeholder="请选择内容位置"
                >
                  <el-option
                    v-for="item in contentPositionOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>

          <!-- 点击事件 -->
          <el-table-column label="点击事件">
            <template #default="scope">
              <el-form-item
                :prop="'datas.' + scope.$index + '.clickEvent'"
                :rules="rules.clickEvent"
              >
                <el-select
                  v-model="scope.row.clickEvent"
                  placeholder="请选择点击事件"
                >
                  <el-option
                    v-for="item in clickEventOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>

          <!-- 操作 -->
          <el-table-column label="操作" width="60">
            <template #default="scope">
              <el-tooltip content="删除" placement="top">
                <el-button
                  link
                  type="primary"
                  icon="Delete"
                  @click="handleDelete(scope.row)"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </el-form>

      <!-- 新增按钮 -->
      <div class="mt-4 flex justify-start">
        <el-button @click="handleButton" type="primary">新增内容</el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">

import JqtOssLibrary from '@/components/JqtOssLibrary/index.vue';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_normal_disable,bus_spread_link_page_mode } = toRefs<any>(proxy?.useDict('sys_normal_disable','bus_spread_link_page_mode'));

export interface ImageTextModeVo {
  //组件类型 text.文字 img.图片
  type?: string;
  //内容 文字或图片
  content?: string;
  //内容位置 0.正常 1.顶部悬浮 2.底部悬浮 3.左侧悬浮 4.右侧悬浮
  contentPosition?: string;
  //点击事件 0.无操作 1.点击跳转链接 2.点击弹窗表单
  clickEvent?: string;
}
/**
 * 表格数据
 */
const datas = ref<ImageTextModeVo[]>([]);
// 表单引用
const formRef = ref();
// 表单根对象（el-form 的 model）
const formData = reactive({ datas: datas.value });

// 动态内容规则（根据 type 决定是否必填）
const getDynamicContentRules = (row) => {
  return [
    {
      required: true,
      message: row.type === 'img' ? '请上传图片' : '请输入文字内容',
      trigger: row.type === 'img' ? 'change' : 'blur',
    },
  ];
};
// 校验规则
const rules = reactive({
  type: [{ required: true, message: '请选择组件类型', trigger: 'change' }],
  contentPosition: [
    { required: true, message: '请选择内容位置', trigger: 'change' },
  ],
  clickEvent: [
    { required: true, message: '请选择点击事件', trigger: 'change' },
  ],
  // content 是动态的，使用 getDynamicContentRules

  // 👇 新增：对 datas 数组本身的校验
  datas: [
    {
      validator: (rule, value, callback) => {
        if (!value || value.length === 0) {
          callback(new Error('请至少添加一条内容'));
        } else {
          callback(); // 校验通过
        }
      },
      trigger: 'blur' // 可手动触发，比如点击“保存”前
    }
  ]
});
// 内容位置
const contentPositionOptions = [
  { label: '正常', value: '0' },
  { label: '顶部悬浮', value: '1' },
  { label: '底部悬浮', value: '2' },
  { label: '左侧悬浮', value: '3' },
  { label: '右侧悬浮', value: '4' }
];
// 点击事件
const clickEventOptions = [
  { label: '无操作', value: '0' },
  { label: '点击跳转链接', value: '1' },
  { label: '点击弹窗表单', value: '2' }
];
const props = defineProps({
  modelValue: Object,
});

onMounted(() => {
// 在初始化时设置 formData
});

const emit = defineEmits(['update:modelValue','confirmCallBack']);
watch(datas, (newVal, oldVal) => {
  emit('update:modelValue', newVal);
  emit('confirmCallBack', newVal);
}, { deep: true, immediate: true });

watch(() => props.modelValue, (newVal) => {
  if (newVal && newVal.length > 0) {
    Object.assign(formData.datas, newVal);
  }
}, { deep: true, immediate: true });


/**
 * 新增按钮点击事件
 */
const handleButton = () => {
  datas.value.push({
    //组件类型 text.文字 img.图片
    type: 'img',
    //内容 文字或图片
    content: undefined,
    //内容位置 0.正常 1.顶部悬浮 2.底部悬浮 3.左侧悬浮 4.右侧悬浮
    contentPosition: '0',
    //点击事件 0.无操作 1.点击跳转链接 2.点击弹窗表单
    clickEvent: '0',
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: ImageTextModeVo) => {
  //删除datas中的数据
  const index = datas.value.indexOf(row);
  if (index > -1) {
    datas.value.splice(index, 1);
  }
}
/**
 * 组件类型改变
 * @param row
 */
const handleChangeType = async(row: ImageTextModeVo) => {
  row.content = '';
}

const validateForm = () => {
  return new Promise((resolve, reject) => {
    if (!formRef.value) {
      reject(new Error('表单引用不存在'));
      return;
    }
    formRef.value.validate(valid => {
      if (valid) {
        resolve(true);
      } else {
        reject(new Error('图文表单填写不完整'));
      }
    });
  });
};

defineExpose({
  validateForm,
});
</script>

<style scoped>
.box-card {
  margin-bottom: 20px; /* 卡片底部间距 */
  border-radius: 10px;
}
</style>
